const app = getApp();
let request = require("../../utils/request.js");
let config = require("../../config/config.js");
var QQMapWx = require("../../utils/qqmap-wx-jssdk.js");
var qqmapsdk = new QQMapWx({ key: config.map_key });
let flag = true;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: 0,
    longitude: 0,
    latitude: 0,
    parkList: [],
    page: 1,
    pageSize: 10,
    isCanNext: true,
    canIUseGetUserProfile: false,
    nearbyBarIndex: 0,
    bannerList: [],
    ticketList: [],
    productList: [],
    merchantList: [],
    token: wx.getStorageSync("token"),
    parkTicket: -1,
    monthCard: -1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("参数:", options);
    if (wx.getUserProfile) {
      this.setData({ canIUseGetUserProfile: true });
    }
    // 获取屏幕高度
    this.setData({
      screenHeight: wx.getSystemInfoSync().screenHeight,
      token: wx.getStorageSync("token"),
      parkTicket: options.parkTicket,
      reserve: options.reserve,
      monthCard: options.monthCard,
    });
    //  获取当前位置
    this.getUserLocation();
    
  },

  /**
   * 顶部导航栏按钮
   */
  selectNearbyBar(e) {
    let index = e.currentTarget.dataset.index;
    if (index == this.data.nearbyBarIndex) {
      return;
    }
    this.setData({
      nearbyBarIndex: index,
    });
  },
  /**
   * swiper组件滑动切换事件
   */
  changeNearbyBar(e) {
    let index = e.detail.current;
    this.setData({
      nearbyBarIndex: index,
    });
  },
  /**
   * 获取用户当前位置
   */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: "gcj02",
      success(res) {
        console.log(res);
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
        //  获取附近停车场
        that.getParks(longitude, latitude);
      },
    });
  },
  /**
   * 领取优惠券
   */
  getCoupon(e) {
    let index = e.currentTarget.dataset.index;
    let ticketList = this.data.ticketList;
    request
      .http("/customer/ticket/receive-ticket", "POST", {
        ticketId: ticketList[index].id,
      })
      .then((res) => {
        let data = res.data;
        if (data.code == 200) {
          wx.showToast({
            title: "领取成功",
          });
        }
      });
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始位置经纬度
   * @param {Array} to 终点位置经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: "driving",
      from,
      to,
      success(res) {
        callback(res);
      },
      fail: function (error) {
        console.error(error);
      },
    });
  },
  /**
   * 在地图中打开
   */
  toMap(e) {
    let index = e.currentTarget.dataset.index;
    let merchantList = this.data.merchantList;
    wx.openLocation({
      latitude: merchantList[index].latitude * 1,
      longitude: merchantList[index].longitude * 1,
      name: merchantList[index].shopName,
      address: merchantList[index].shopAddress,
    });
  },
  /**
   * 获取用户信息
   */
  getUserProfile(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.setData({
          userInfo: res.userInfo,
        });
        wx.setStorageSync("userInfo", res.userInfo);
        wx.login({
          success: (res) => {
            that.getToken(res.code, index);
          },
        });
      },
    });
  },
  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   * @param {Number} index 当前专属停车按钮索引
   */
  getToken(code) {
    let that = this;
    let info = this.data.userInfo;
    let url = "/customer/info/authorize";
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? "UNKNOWN" : info.gender == 1 ? "MEN" : "WOMEN",
    };
    request.http(url, "POST", params).then((res) => {
      var data = res.data;
      if (data.code == 200) {
        let token = data.data.token;
        console.log(token)
        // let parkData = this.data.parkList[index]
        wx.setStorageSync("token", token);
        wx.setStorageSync("customerId", data.data.customerId);
        that.setData({ token: token });
        //判断是不是新用户，新用户授权后跳转 绑定车牌页面
        if (data.data.isNew == 1) {
          wx.navigateTo({ url: "../licencePlate/licencePlate" });
        }
      }
    });
  },

  /**
   * 获取附近停车场
   * @param {Number} longitude 经度
   * @param {Number} latitude 纬度
   */
  async getParks(longitude, latitude) {
    if (!this.data.isCanNext) {
      return;
    }
    let params = {
      longitude: longitude,
      latitude: latitude,
      currentPage: this.data.page,
      pageSize: this.data.pageSize,
    };
    let url = "/park/info/getBeiGuoReservePark";
    const { data: res } = await request.http(url, "GET", params);
    console.log(res);
    if (res.code == 200) {
      let parkList = res.data.records;
      for (var i = 0; i < parkList.length; i++) {
        if (parkList[i].parkImgUrl) {
          let index = parkList[i].parkImgUrl.split(",")[0].lastIndexOf(".");
          let name = parkList[i].parkImgUrl.split(",")[0].substr(0, index);
          let ext = parkList[i].parkImgUrl.split(",")[0].substr(index + 1);
          parkList[i].parkImgUrl = name + "@_@350." + ext;
        } else {
          parkList[i].parkImgUrl =
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017bcb58b4db5fa801219c7719b5ff.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631772791&t=f97c88d0443ed9fe68c2ee2a27ee5096";
        }
      }
      this.setData({
        parkList: res.data.records,
      });
    }
  },

  /**
   * 在地图中打开
   */
  toMapNavigation(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    let parkData = this.data.parkList[index];
    let latitude = Number(parkData.latitude);
    let longitude = Number(parkData.longitude);
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14,
    });
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始位置经纬度
   * @param {Array} to 终点位置经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    if (to.length <= 0) {
      return;
    }
    qqmapsdk.calculateDistance({
      mode: "driving",
      from,
      to,
      success(res) {
        callback(res);
      },
      fail: function (error) {
        console.error(error);
      },
    });
  },
  /**
   * 跳转到预约页面
   */
  toReserve(e) {
    console.log("跳转到预约页面：", e);
    if (e.currentTarget.dataset.park.reserveParkSpace == 0) {
      wx.showToast({
        title: "当前可预约车位为0，请选择其他停车场",
        icon: "none",
      });
      return;
    }
    if (this.data.token) {
      wx.navigateTo({
        url:
          "/pages/subscribe/subscribe?parkId=" +
          e.currentTarget.dataset.park.id +
          "&parkName=" +
          e.currentTarget.dataset.park.parkName,
      });
    } else {
      //  获取用户信息
      this.getUserProfile(
        "/pages/subscribe/subscribe?parkId=" +
          e.currentTarget.dataset.park.id +
          "&parkName=" +
          e.currentTarget.dataset.park.parkName
      );
    }
  },
  /**
   * 跳转到领取停车券页面：
   */
  toReceiveTicket(e) {
    console.log("跳转到领取停车券页面：", e);
    if (this.data.token) {
      wx.navigateTo({
        url:
          "/pages/park-ticket/parkTicket?parkId=" +
          e.currentTarget.dataset.park.id,
      });
    } else {
      //  获取用户信息
      this.getUserProfile(
        "/pages/park-ticket/parkTicket?parkId=" +
          e.currentTarget.dataset.park.id
      );
    }
  },
  /**
   * 获取用户信息
   */
  getUserProfile(url) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({ userInfo: res.userInfo });
        wx.setStorageSync("userInfo", res.userInfo);
        wx.login({
          success: (res) => {
            this.getToken(res.code, url);
          },
        });
      },
    });
  },

  /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   */
  getToken(code, src) {
    let info = this.data.userInfo;
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? "UNKNOWN" : info.gender == 1 ? "MEN" : "WOMEN",
    };
    request.http("/customer/info/authorize", "POST", params).then((res) => {
      var data = res.data;
      if (data.code == 200) {
        let token = data.data.token;
        wx.setStorageSync("token", token);
        wx.setStorageSync("customerId", data.data.customerId),
          this.setData({
            token,
            userInfo: wx.getStorageSync("userInfo"),
            websocketUrl: app.globalData.websocketUrl + data.data.customerId,
          });

        //  授权后，跳转页面
        if (src) {
          wx.navigateTo({ url: src });
        }
      } else {
        wx.removeStorageSync("userInfo");
      }
    });
  },
});
